using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace XP.Utilities.Utility.DataReader
{
    public class CSVReader : IInputDataReader
    {
        /// <summary>
        /// Read CSV
        /// </summary>
        /// <param name="filePathName"></param>
        /// <returns></returns>
        public List<string[]> ReadFile(string filePath)
        {
            List<String[]> ls = new List<String[]>();
            StreamReader fileReader = new StreamReader(filePath, Encoding.Default);
            string strCont = fileReader.ReadToEnd();
            fileReader.Close();
            fileReader = null;
            string[] lines = Regex.Split(strCont, "\r\n");
            string strLine;
            for (int i = 0; i < lines.Length; i++)
            {
                strLine = lines[i];
                if (!String.IsNullOrEmpty(strLine))
                {
                    strLine = strLine.Replace("\"\"", "D##") + ",";
                    strLine = strLine.Replace("\n", " ");
                    strLine = strLine.Replace("\r", " ");
                    if (strLine.IndexOf("553266") >= 0)
                    {
                        Console.WriteLine(strLine);
                    }
                    Match match = Regex.Match(strLine, "(\"[^\"]*(\"{2})*[^\"]*\")*([^,]*,)", RegexOptions.IgnoreCase);
                    List<string> strList = new List<string>();
                    while (match.Success)
                    {
                        string value = match.Value.TrimEnd(',').Replace("\"", "").Replace("D##", "\"").Trim();
                        if (i == 0 && string.IsNullOrEmpty(value))
                        {
                            match = match.NextMatch();
                            continue;
                        }
                        strList.Add(value);
                        match = match.NextMatch();
                    }
                    if (ls.Count>0 && strList.Count < ls[0].Length)
                    {
                        while (ls[0].Length > strList.Count)
                        {
                            strList.Add("");
                        }
                    }
                    ls.Add(strList.ToArray());
                }
            }
            return ls;
        }
    }
}
